<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> 维保计划 </span>
      </template>
      <template #toolbar>
        <!-- <a-button
         type="primary"
         @click="handleForm({})"
         v-auth="'maintenance:management:inMaintenanceInfo:edit'"
         >
          <Icon icon="i-fluent:add-12-filled" /> {{ t('新增') }}
        </a-button> -->
      </template>
      <template #firstColumn="{ record }" >
        <a @click="handleForm({ tid: record.tid })">
          {{ record.title }}
          <!-- {{record.tid}} -->
        </a>
      </template>
      <!-- 新增 action 插槽 -->
      <template #action="{ record }">
        <a-button @click="handleForm({ tid: record.tid })" type="text">
          <span style="font-size: 14px; color: #4169E1;">详情</span>
        </a-button>
        <Popconfirm
          title="是否确认删除该维保计划"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handleDelete(record)"
          @cancel="handleCancel"
        >
          <a-button 
            v-auth="'maintenance:management:inMaintenanceInfo:edit'" 
            type="text" 
            style="color: red;"
          >
            <span style="font-size: 14px;">删除</span>
          </a-button>
        </Popconfirm>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup name="ViewsMaintenanceManagementInMaintenanceInfoList">
  import { unref, ref, onMounted } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { inMaintenanceInfoDelete, inMaintenanceInfoListData } from '/@/api/maintenance.management/inMaintenanceInfo';
  import { unitEnterpriseDominantListData } from '/@/api/unitmanage/unitEnterpriseDominant';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import { officeTreeData } from '/@/api/sys/office';
  import InputForm from './form.vue';
  import { registerCoordinateSystem } from 'echarts';
  import dayjs from 'dayjs'; // 引入 dayjs
  import { Popconfirm } from 'ant-design-vue'; // 引入 Popconfirm 组件

  const { t } = useI18n('maintenance.management.inMaintenanceInfo');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const route = router.currentRoute;

  const getTitle = {
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: meta.title || t('维保任务信息表管理'),
  };

  const inMaintenanceInfoParams = ref({
    title: ''
  })

  const EnterpriseParams = ref<Recordable>({
    name: ''
  });

  const maintenanceEnterpriseParams = ref<Recordable>({
    name: '',
    dominantType:'maintenance'
  });

  const searchForm: FormProps = {
    baseColProps: { md: 8, lg: 6 },
    labelWidth: 90,
    schemas: [
      {
        label: t(''),
        field: 'id',
        fieldLabel: 'title',
        component: 'Select',
        componentProps: {
          placeholder: t('请输入任务名称'),
          api: inMaintenanceInfoListData,
          resultField: 'list',
          fieldNames: { label: 'title', value: 'id' },
          params: inMaintenanceInfoParams,
          allowClear: true,
          immediate: false,
          each: false,
          showSelect: true,
          optionFilterProp: 'label',
          showSearch: true,
          onSearch: (value) => {
            inMaintenanceInfoParams.value.title = value;
            reload()
        },
        }
      },
      {
        label: t(''),
        field:'maintenanceEnterpriseId',
        fieldLabel:'maintenanceEnterpriseName',
        component: 'Select',
        componentProps: () => {
        return {
          placeholder: t('请输入维保企业'),
          api: unitEnterpriseDominantListData,
          params: maintenanceEnterpriseParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          filterTreeNode: false,
          allowClear: true,
          filterOption: false,
          immediate: true,
          onSearch: (value: string) => {
            maintenanceEnterpriseParams.value.name = value;
            console.log(maintenanceEnterpriseParams.value);
          },
        };
      },
      },
      {
        label: t(''),
        field: 'userName',
        component: 'Input',
        componentProps: {
          placeholder: t('请输入维保人员姓名'),
        },
      },
      {
        label: t(''),
        field: 'enterpriseId',
        fieldLabel: 'enterpriseName',
        component: 'TreeSelect',
        componentProps: () => {
        return {
          placeholder: t('请输输入业主企业'),
          api: unitEnterpriseDominantListData,
          params: EnterpriseParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          filterTreeNode: false,
          allowClear: true,
          filterOption: false,
          immediate: true,
          onSearch: (value: string) => {
            EnterpriseParams.value.name = value;
            console.log(EnterpriseParams.value);
          },
        };
      },
      },
      // {
      //   label: t(''),
      //   field:'state',
      //   component: 'Input',
      //   componentProps: {
      //     placeholder: t('请输入检测状态'),
      //   },
      // },
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('任务标题'),
      dataIndex: 'title',
      key: 'a.title',
      sorter: true,
      width: 230,
      align: 'left',
      slot: 'firstColumn',
    },
    {
      title: t('维保企业名称'),
      dataIndex:'maintenanceEnterpriseName',
      key: 'a.maintenance_enterprise_name',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('维保人员姓名'),
      dataIndex: 'userName',
      key: 'a.user_name',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('业主企业名称'),
      dataIndex: 'enterpriseName',
      key: 'a.enterprise_name',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('状态'),
      dataIndex:'state',
      key: 'a.state',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('执行开始时间'),
      dataIndex:'startExecuteTime',
      key: 'a.start_execute_time',
      customRender: ({ text }) => {
        return text && dayjs(text).isValid()? dayjs(text).format('YYYY-MM-DD') : '';
      },
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('任务完成时间'),
      dataIndex: 'completeTime',
      key: 'a.complete_time',
      customRender: ({ text }) => {
        return text && dayjs(text).isValid()? dayjs(text).format('YYYY-MM-DD') : '';
      },
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('维保任务开始年月'),
      dataIndex: 'taskStartDate',
      key: 'a.task_start_date',
      customRender: ({ text }) => {
        return text && dayjs(text).isValid()? dayjs(text).format('YYYY-MM-DD') : '';
      },
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('维保任务结束年月'),
      dataIndex: 'taskEndDate',
      key: 'a.task_end_date',
      customRender: ({ text }) => {
        return text && dayjs(text).isValid()? dayjs(text).format('YYYY-MM-DD') : '';
      },
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('操作'),
      dataIndex: 'action',
      key: 'action',
      width: 160,
      fixed: 'right',
      slot: 'action'
    }
  ];

  const [registerTable, { reload }] = useTable({
    api: inMaintenanceInfoListData,
    beforeFetch: (params) => {
    //   const urlParams = new URLSearchParams(router.currentRoute.value.fullPath.split('?')[1]);
    //   const maintenanceEnterpriseName = urlParams.get('maintenanceEnterpriseName');
    //   const id = urlParams.get('id'); // 获取 id 参数
    //   if (maintenanceEnterpriseName) {
    //     maintenanceEnterpriseParams.value.name = decodeURIComponent(maintenanceEnterpriseName);
    //     params.maintenanceEnterpriseName = maintenanceEnterpriseParams.value.name;
    //   }
    //   if (id) {
    //   params.id = id; // 将 id 参数添加到请求参数中
    // }
      return params;
    },
    columns: tableColumns,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
  });

  const [registerDrawer, { openDrawer }] = useDrawer();

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  async function handleDelete(record: Recordable) {
    const params = { tid: record.tid };
    const res = await inMaintenanceInfoDelete(params);
    showMessage(res.message);
    handleSuccess(record);
  }

  function handleSuccess(record: Recordable) {
    reload({ record });
  }

  function handleCancel() {
    console.log('取消删除操作');
  }

  onMounted(() => {
    const tid = unref(route).query.tid;
    if (tid) {
      handleForm({ tid });
    }
  });
</script>    